package durose.system.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import durose.system.pojo.Sys_menu;
import durose.system.service.Sys_menuService;
import durose.util.ImageUtil;

/**
 * 首页跳转
 * @author Administrator
 *
 */
@Controller
public class NavIndexController {
	
	String prefix = "system/durose/";
	//图片上传下载目录
	String uploadPath ="static/img";
	
	@Autowired 
	 Sys_menuService sys_menuService;

	/**
	 * 首页跳转
	 * @param model
	 * @return
	 */
	@RequestMapping("/")
	public String toIndex(Model model){
		List<Sys_menu> sys_menus =initSys_menus(sys_menuService.sys_menuList(""));
		model.addAttribute("sys_menus", sys_menus);
		return "index";
	}
	/**
	 * 跳转到图标管理
	 * @return
	 */
	@RequestMapping("durose_icon")
	public String toIcon(){
		return prefix+"durose_icon";
	}
	/**
	 * 跳转到提供的附加组件页面
	 * @return
	 */
	@RequestMapping("durose_extra")
	public String toExtra(){
		return prefix+"durose_extra";
	}
	/**
	 * 跳转到首页管理
	 */
	@RequestMapping("durose_index")
	public String toIndexDiv(){
		return prefix+"durose_index";
	}
	
	/**
	 * 图片上传
	 */
	@RequestMapping("durose_upload_picture")
	@ResponseBody
	public String uploadPic(@RequestParam("file") MultipartFile file,HttpServletRequest request){
		String path = request.getServletContext().getRealPath("/")+File.separator+uploadPath;
		String pictureName = UUID.randomUUID().toString() +"."+ file.getOriginalFilename().split("\\.")[1];
		File f = new File(path,pictureName);
		if(!f.getParentFile().exists()){
			f.mkdirs();
		}
		try {
			file.transferTo(f);
		} catch (Exception e) {
			e.printStackTrace();
		}
        ImageUtil.resizeImage(f, 128, 128, f);
		return pictureName;
	}
	
	
	/**
	 * 对返回的菜单列表进行包装，返回父+子的菜单形式
	 */
	private List<Sys_menu> initSys_menus(List<Sys_menu> sys_menus){
		List<Sys_menu> sys_menuNew = new ArrayList<Sys_menu>();
		for(Sys_menu sys_menu: sys_menus){
			//如果是父目录
			if(sys_menu.getMenu_parent()==0){
				//找到它对应下的子目录
				for(Sys_menu sys_menu1:sys_menus){
					if(sys_menu1.getMenu_parent()==sys_menu.getMenu_id()){
						sys_menu.getSys_menus().add(sys_menu1);
					}
				}
				sys_menuNew.add(sys_menu);
			}
		}
		return sys_menuNew;
	}
}
